import functools
import logging
import time
import traceback
from functools import wraps


# 日志装饰器
def log_decorator(func):
    logger = logging.getLogger(__name__)

    @wraps(func)
    def wrapper(*args, **kwargs):
        try:
            logger.info(f'{func.__name__}开始运行')
            # 执行原函数
            result = func(*args, **kwargs)
            logger.info(f'{func.__name__}运行结束')
            return result
        except Exception as e:
            # 获取当前执行的代码行信息
            tb = traceback.extract_stack(limit=2)
            line_info = tb[-2]
            logger.error(f'Error in {func.__name__} at line {line_info.lineno}: {e}')
            raise

    return wrapper


# 方法失败重试装饰器
def retry(retry_times=2, delay=2, allowed_exceptions=Exception):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            for _ in range(retry_times):
                try:
                    return func(*args, **kwargs)
                except allowed_exceptions as e:
                    print(f"Exception: {e}, retrying in {delay} seconds...")
                    time.sleep(delay)
        return wrapper
    return decorator
